<template>
  <div class="attendance-container">
    <h1>教师考勤管理</h1>
    
    <!-- 显示当前用户信息 -->
    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }} (教师)</p>
      <router-link to="/teacher/dashboard">返回Dashboard</router-link>
    </div>

    <div class="absent-students-section">
      <h2>未打卡学生列表</h2>
      <div class="date-selector">
        <label for="absentDate">选择日期:</label>
        <input type="date" id="absentDate" v-model="absentDate" />
        <button @click="loadAbsentStudents" class="refresh-btn">查询</button>
      </div>
      <table class="students-table">
        <thead>
          <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>班级</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="student in absentStudents" :key="student.studentNumber">
            <td>{{ student.studentNumber }}</td>
            <td>{{ student.fullName }}</td>
            <td>{{ student.gender }}</td>
            <td>{{ student.classId }}</td>
            <td>
              <button @click="generateLeaveCode(student)" class="generate-code-btn">生成请假码</button>
              <button @click="deleteLeaveCode(student)" class="delete-code-btn">删除请假码</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>


    <!-- 请假码显示区域 -->
    <div v-if="currentLeaveCode" class="leave-code-section">
      <h2>请假码</h2>
      <div class="code-display">
        <p>学生 {{ currentStudentName }} 的请假码:</p>
        <div class="code">{{ currentLeaveCode }}</div>
        <button @click="copyLeaveCode" class="copy-btn">复制请假码</button>
      </div>
    </div>

    <!-- 请假申请管理 -->
    <div class="leave-management-section">
      <h2>请假申请管理</h2>
      <!-- 搜索条件 -->
      <div class="search-filters">
        <div class="filter-row">
          <div class="form-group">
            <label for="searchStudentNumber">学生学号:</label>
            <input type="text" id="searchStudentNumber" v-model="searchForm.studentNumber" placeholder="请输入学生学号" />
          </div>
          <div class="form-group">
            <label for="searchStudentName">学生姓名:</label>
            <input type="text" id="searchStudentName" v-model="searchForm.studentName" placeholder="请输入学生姓名" />
          </div>
          <div class="form-group">
            <label for="searchStartDate">开始日期:</label>
            <input type="date" id="searchStartDate" v-model="searchForm.startDate" />
          </div>
          <div class="form-group">
            <label for="searchEndDate">结束日期:</label>
            <input type="date" id="searchEndDate" v-model="searchForm.endDate" />
          </div>
          <div class="form-group">
            <label for="searchStatus">状态:</label>
            <select id="searchStatus" v-model="searchForm.status">
              <option value="">全部</option>
              <option value="1">等待审批</option>
              <option value="2">撤销审批</option>
              <option value="3">等待系统更新</option>
              <option value="4">已完成</option>
              <option value="5">不批准</option>
            </select>
          </div>
        </div>
        <div class="filter-actions">
          <button @click="loadLeaveApplications" class="search-btn">查询</button>
          <button @click="resetSearchForm" class="reset-btn">重置</button>
        </div>
      </div>

      <!-- 请假申请列表 -->
      <div class="leave-applications">
        <table class="leave-table">
          <thead>
            <tr>
              <th>学号</th>
              <th>学生姓名</th>
              <th>开始日期</th>
              <th>结束日期</th>
              <th>请假原因</th>
              <th>申请时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="leave in leaveApplications" :key="leave.id">
              <td>{{ leave.studentNumber }}</td>
              <td>{{ leave.studentName }}</td>
              <td>{{ leave.startDate }}</td>
              <td>{{ leave.endDate }}</td>
              <td>{{ leave.remarks }}</td>
              <td>{{ leave.createTime }}</td>
              <td>
                <span class="status-badge" :class="getStatusClass(leave.status)">
                  {{ getStatusText(leave.status) }}
                </span>
              </td>
              <td>
                <div v-if="leave.status === '1' || leave.status === '3'" class="action-buttons">
                  <button @click="approveLeave(leave.id, '4')" class="approve-btn">批准</button>
                  <button @click="approveLeave(leave.id, '5')" class="reject-btn">不批准</button>
                </div>
                <div v-else>
                  无操作
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <div v-if="leaveApplications.length === 0" class="no-data">
          暂无请假申请记录
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>

    <!-- 成功提示 -->
    <div v-if="success" class="success-message">
      {{ success }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  name: 'TeacherAttendance',
  setup() {
    // 用户信息
    const userProfile = ref({});
    
    // 未打卡学生列表
    const absentStudents = ref([]);
    
    // 查询日期
    const absentDate = ref(new Date().toISOString().split('T')[0]); // 默认今天
    
    // 手动操作表单
    const manualForm = ref({
      studentNumber: '',
      leaveDate: new Date().toISOString().split('T')[0] // 默认今天
    });
    
    // 请假码相关
    const currentLeaveCode = ref('');
    const currentStudentName = ref('');
    
    // 请假申请搜索表单
    const searchForm = ref({
      studentNumber: '',
      studentName: '',
      startDate: '',
      endDate: '',
      status: ''
    });
    
    // 请假申请列表
    const leaveApplications = ref([]);
    
    // 状态信息
    const error = ref('');
    const success = ref('');

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
        } else {
          error.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 获取未打卡学生列表
    const loadAbsentStudents = async () => {
      try {
        const url = `/teacher/absent-students${absentDate.value ? `?date=${absentDate.value}` : ''}`;
        const response = await fetch(url, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          absentStudents.value = result.data || [];
        } else {
          error.value = result.msg || '获取未打卡学生列表失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 生成请假码（基于学生列表）
    const generateLeaveCode = async (student) => {
      try {
        const url = `/teacher/leave/code?studentNumber=${student.studentNumber}${absentDate.value ? `&leaveDate=${absentDate.value}` : ''}`;
        const response = await fetch(url, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          currentLeaveCode.value = result.data;
          currentStudentName.value = student.fullName;
          success.value = `请假码生成成功`;
        } else {
          error.value = result.msg || '生成请假码失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 删除请假码（基于学生列表）
    const deleteLeaveCode = async (student) => {
      try {
        const params = new URLSearchParams();
        params.append('studentNumber', student.studentNumber);
        if (absentDate.value) {
          params.append('leaveDate', absentDate.value);
        }
        
        const response = await fetch('/teacher/leave/code/delete', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: params
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '请假码删除成功';
          // 如果删除的是当前显示的请假码，则清空
          if (currentStudentName.value === student.fullName) {
            currentLeaveCode.value = '';
            currentStudentName.value = '';
          }
        } else {
          error.value = result.msg || '删除请假码失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 手动生成请假码
    const generateLeaveCodeManual = async () => {
      if (!manualForm.value.studentNumber) {
        error.value = '请输入学生学号';
        return;
      }
      
      try {
        const url = `/teacher/leave/code?studentNumber=${manualForm.value.studentNumber}${manualForm.value.leaveDate ? `&leaveDate=${manualForm.value.leaveDate}` : ''}`;
        const response = await fetch(url, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          currentLeaveCode.value = result.data;
          currentStudentName.value = manualForm.value.studentNumber;
          success.value = `请假码生成成功`;
        } else {
          error.value = result.msg || '生成请假码失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 手动删除请假码
    const deleteLeaveCodeManual = async () => {
      if (!manualForm.value.studentNumber) {
        error.value = '请输入学生学号';
        return;
      }
      
      try {
        const params = new URLSearchParams();
        params.append('studentNumber', manualForm.value.studentNumber);
        if (manualForm.value.leaveDate) {
          params.append('leaveDate', manualForm.value.leaveDate);
        }
        
        const response = await fetch('/teacher/leave/code/delete', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: params
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '请假码删除成功';
          // 如果删除的是当前显示的请假码，则清空
          if (currentStudentName.value === manualForm.value.studentNumber) {
            currentLeaveCode.value = '';
            currentStudentName.value = '';
          }
        } else {
          error.value = result.msg || '删除请假码失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 复制请假码到剪贴板
    const copyLeaveCode = () => {
      navigator.clipboard.writeText(currentLeaveCode.value)
        .then(() => {
          success.value = '请假码已复制到剪贴板';
        })
        .catch(() => {
          error.value = '复制失败，请手动复制';
        });
    };

    // 获取请假申请列表
    const loadLeaveApplications = async () => {
      try {
        const searchParams = {
          studentNumber: searchForm.value.studentNumber || null,
          studentName: searchForm.value.studentName || null,
          startDate: searchForm.value.startDate || null,
          endDate: searchForm.value.endDate || null,
          status: searchForm.value.status || null
        };

        const response = await fetch('/teacher/leave-students', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(searchParams)
        });

        const result = await response.json();
        if (result.code === 1) {
          leaveApplications.value = result.data || [];
        } else {
          error.value = result.msg || '获取请假申请列表失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 批准/不批准请假申请
    const approveLeave = async (leaveId, status) => {
      try {
        const params = new URLSearchParams();
        params.append('leaveId', leaveId);
        params.append('status', status);

        const response = await fetch('/teacher/update-leave', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: params
        });

        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '操作成功';
          // 重新加载请假申请列表
          await loadLeaveApplications();
        } else {
          error.value = result.msg || '操作失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 重置搜索表单
    const resetSearchForm = () => {
      searchForm.value = {
        studentNumber: '',
        studentName: '',
        startDate: '',
        endDate: '',
        status: ''
      };
    };

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        '1': '等待审批',
        '2': '撤销审批',
        '3': '等待系统更新',
        '4': '已完成',
        '5': '不批准'
      };
      return statusMap[status] || '未知状态';
    };

    // 获取状态样式类
    const getStatusClass = (status) => {
      const classMap = {
        '1': 'status-pending',
        '2': 'status-cancelled',
        '3': 'status-processing',
        '4': 'status-completed',
        '5': 'status-rejected'
      };
      return classMap[status] || 'status-unknown';
    };

    // 初始化
    onMounted(async () => {
      await loadUserProfile();
      await loadAbsentStudents();
      // 默认加载请假申请列表
      await loadLeaveApplications();
    });

    return {
      userProfile,
      absentStudents,
      absentDate,
      manualForm,
      currentLeaveCode,
      currentStudentName,
      searchForm,
      leaveApplications,
      error,
      success,
      loadAbsentStudents,
      generateLeaveCode,
      deleteLeaveCode,
      generateLeaveCodeManual,
      deleteLeaveCodeManual,
      copyLeaveCode,
      loadLeaveApplications,
      approveLeave,
      resetSearchForm,
      getStatusText,
      getStatusClass
    };
  }
};
</script>

<style scoped>
.attendance-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.absent-students-section, .manual-leave-code-section, .leave-code-section, .leave-management-section {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.date-selector, .manual-form, .filter-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.date-selector label, .form-group label {
  font-weight: bold;
}

.date-selector input, .form-group input, .form-group select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group {
  display: flex;
  flex-direction: column;
  margin-right: 15px;
}

.form-buttons, .filter-actions {
  display: flex;
  gap: 10px;
}

.refresh-btn, .generate-code-btn, .delete-code-btn, .copy-btn, 
.search-btn, .reset-btn, .approve-btn, .reject-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.refresh-btn {
  background-color: #9E9E9E;
  color: white;
}

.generate-code-btn, .approve-btn {
  background-color: #4CAF50;
  color: white;
}

.delete-code-btn, .reject-btn {
  background-color: #f44336;
  color: white;
}

.search-btn {
  background-color: #2196F3;
  color: white;
}

.reset-btn {
  background-color: #FF9800;
  color: white;
}

.students-table, .leave-table {
  width: 100%;
  border-collapse: collapse;
}

.students-table th, .students-table td, .leave-table th, .leave-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.students-table th, .leave-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.leave-table td {
  vertical-align: top;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.approve-btn, .reject-btn {
  padding: 4px 8px;
  font-size: 12px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.status-processing {
  background-color: #cce7ff;
  color: #004085;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-rejected {
  background-color: #f8d7da;
  color: #721c24;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #666;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}
</style>